﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml.Data;

namespace Emilie.Converters
{
    /// <summary>
    /// Allows you to take only a given amount of items from an enumerable collection. 
    /// Possibly useful on hub page designs, applied to an ItemsControl ItemsSource
    /// </summary>
    public class EnumerableTakeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            // Default number of items to take
            int totake = -1;

            // Overwrite with custom parameter if given
            if (parameter != null)
            {
                try
                {
                    totake = System.Convert.ToInt32(parameter);
                }
                catch { }
            }

            var generic = value as IEnumerable;
            if (generic != null && totake != -1)
            {
                return generic.Cast<object>().Take(totake);
            }

           
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

